from collections import OrderedDict

from goods.models import GoodsChannel


def get_categories():
    '''展示首页广告'''
    '''展示频道和分类'''
    '''准备商品分类对应的字典'''
    categories = OrderedDict()
    '''从商品分类开始入手，因为向上可以差类型分组，向下可以差详细类型'''
    channels = GoodsChannel.objects.order_by('group_id' ,'sequence')
    '''查询所有商品分类'''
    for channel in channels:
        '''遍历商品分类，获取当前所在的组'''
        group_id = channel.group_id
        if group_id not in categories:
            '''构造基本的数据框架(字典【keys】 = value'''
            categories[group_id] = {'channels' :[] ,'sub_cats' :[]}
        cat1 = channel.  category  # 寻找当前频道的一级类别
        '''讲cat1追加到channel'''
        categories[group_id]['channels'].append({
            'id': cat1.id,
            'name' :cat1.name,
            'url' :channel.url,
        })
        # 查询二级和三级类别
        for cat2 in cat1.subs.all():
            cat2.sub_cats = []
            for cat3 in cat2.subs.all():
                '''把三级类别添加到2及类别中的sub_cats中'''
                cat2.sub_cats.append(cat3)
            '''将查询到的2及类别添加到一级类别的 sbu_cats中'''
            categories[group_id]['sub_cats'].append(cat2)
    return categories